package App.Utility;

import App.Config.JsonWebTokenConfig;
//import App.Config.JwtConfig;
//import App.Config.JwtManager;
import App.Model.Account.CrmUser;
import App.Model.Account.JWTResponse;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by xw on 2018/11/21.
 */

@Component
@AllArgsConstructor
public class JwtAuth {

    private final JsonWebTokenConfig _jwtConfig;

    //更具登陆用户，生成token字符串
    public String buildToken(int userId, String userName) {

        Long now = System.currentTimeMillis();
        Claims _claims = Jwts.claims();
        _claims.put("uid", userId);
        _claims.put("username", userName);
        String _secrete = _jwtConfig.getSecret();
        String token = Jwts.builder()
                .setSubject(userName)
                .setClaims(_claims)
                .setIssuer("crm")
                .setIssuedAt(new java.util.Date(now))
                .setExpiration(new java.util.Date(System.currentTimeMillis() + _jwtConfig.getExpiration()))
                .signWith(SignatureAlgorithm.HS256, _secrete)
                .compact();
        return token;
    }


    public JWTResponse buildTokenNew(int userId, String userName) {
        System.out.println(JSONObject.toJSON(_jwtConfig));
        Date _expirationDate = new java.util.Date(System.currentTimeMillis() + _jwtConfig.getExpiration());
        Long now = System.currentTimeMillis();
        Claims _claims = Jwts.claims();
        _claims.put("uid", userId);
        _claims.put("username", userName);
        String _secrete = _jwtConfig.getSecret();
        String token = Jwts.builder()
                .setSubject(userName)
                .setClaims(_claims)
                .setIssuer("crm")
                .setIssuedAt(new java.util.Date(now))
                .setExpiration(_expirationDate)
                .signWith(SignatureAlgorithm.HS256, _secrete)
                .compact();


        JWTResponse _jwtResponse = new JWTResponse();
        _jwtResponse.setToken(token);
        _jwtResponse.setExpiretionDate(_expirationDate);
        return _jwtResponse;
    }


    //获取token中的用户数据
    public CrmUser getTokenUserInfo(String token) {
        CrmUser _userInfo = new CrmUser();
        try {

            String _secret = _jwtConfig.getSecret();
            //解析token
            Jws<Claims> _claims = Jwts.parser()
                    .setSigningKey(_secret)
                    .parseClaimsJws(token.replace("Bearer ", ""));

            if (_claims != null) {
                int _userId = 0;
                String _userName = "";
                if (_claims.getBody().containsKey("uid")) {
                    Object tempId = _claims.getBody().get("uid");
                    if (tempId != null) {
                        _userId = Integer.parseInt(tempId.toString());
                    }
                }
                if (_claims.getBody().containsKey("username")) {
                    Object tempName = _claims.getBody().get("username");
                    if (tempName != null) {
                        _userName = tempName.toString();
                    }
                }
                _userInfo.setId(_userId);
                _userInfo.setUsername(_userName);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _userInfo;
    }

    //end of class
}
